﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.Windows.Shapes;
using System.Xml;
using System.Web;
using System.IO;
using System.Net;
using System.Threading;
using System.Security.Cryptography;
using System.Xml.Serialization;
using System.Windows.Resources;
using System.Diagnostics;

namespace SpyTxT
{
    public partial class Window1 : Window, IUIAction
    {
        private StateManager statemanager = new StateManager();
        private DoXMLManager doxmlmanger = new DoXMLManager();

        private DispatcherTimer dTimer = new System.Windows.Threading.DispatcherTimer();

        private CheckNet checknet = new CheckNet();
        private GetLoginTicketNet getloginticket = new GetLoginTicketNet();
        private SoftInfUpdataNet softinfupdatanet = new SoftInfUpdataNet();
        private GetQQPictureNet qqlogin = new GetQQPictureNet();

        private DoCanConnectXML docanconnectxml = new DoCanConnectXML();
        private DoGetLoginTicketXML dogetloginticketxml = new DoGetLoginTicketXML();
        private DoGetTXTXML dogettxtxml = new DoGetTXTXML();
        private DoSoftInfUpdataXML dosoftinfupdataxml = new DoSoftInfUpdataXML();

        private CityPeiHuoManager citypeihuomanager = new CityPeiHuoManager();
        //private MyAreaList myarealist = null;
        private rootmylist rootmylist = null;
        private Config config = null;
        private AreaCityListTree areacitylistree = new AreaCityListTree();
        private AreaListTree arealisttree = new AreaListTree();
        private GuoLianNet guoliannet = new GuoLianNet();

        private Hashtable mapguoliannet = new Hashtable();

        public string ticketbylogin = null;
        public string selectcityname = null;
        public Boolean bLoginOk = false;

        private DebugInfoListTemple debuginfolist = new DebugInfoListTemple();

        public Area areastate = new Area();

        TextBox tbox = new TextBox();
 

        public Window1()
        {
            InitializeComponent();


            getloginticket.InitUIAction(this);
            checknet.InitUIAction(this);
            docanconnectxml.InitUIAction(this);
            dogetloginticketxml.InitUIAction(this);
            dogettxtxml.InitUIAction(this);
            softinfupdatanet.InitUIAction(this);
            dosoftinfupdataxml.InitUIAction(this);
            guoliannet.InitUIAction(this);
            //             statemanager.AddStateImp(StateManager.STATE_MODE.STATE_CHECK_NET,docanconnectxml);
            // 

            statemanager.AddStateImp(StateManager.STATE_MODE.STATE_UPDATA_WULIU, guoliannet);
            statemanager.SetState(StateManager.STATE_MODE.STATE_UPDATA_WULIU);
            //FileStream file = new FileStream("mylist.xml", FileMode.Open);

            //StreamReader ms = new StreamReader(file, Encoding.Default);


            //try
            //{
            //    XmlSerializer objSerializer = new XmlSerializer(typeof(MyAreaList));

            //    myarealist = (MyAreaList)objSerializer.Deserialize(ms);
            //}
            //catch (System.Exception ex)
            //{
            //    System.Diagnostics.Debug.WriteLine(ex.Message);
            //}
            //file.Close();

            //ms.Close();

            //foreach (Area a in myarealist.list.arealist)
            //{
            //    areacitylistree.Add(a);
            //}

            //this.treeView1.ItemsSource = areacitylistree;

            ///////////////////////////////////////////////////////////////////
            // 读取配置
            ReadConfig();
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                // 得到启动参数的帐号
                guoliannet.Loginaccount = args[1];

                if (guoliannet.Loginaccount.Length > 0)
                {
                    for (int i = 0; i < config.list.accountset.Count; i++)
                    {
                        if (config.list.accountset[i].account.account == guoliannet.Loginaccount)
                        {
                            guoliannet.Computerkey = config.list.accountset[i].computerkey.ToString();
                            guoliannet.Loginusername = config.list.accountset[i].account.ToString();
                            guoliannet.Loginpassword = config.list.accountset[i].password.ToString();
                            guoliannet.Selectcity = config.list.accountset[i].listencity.initcity;
                            guoliannet.Loginaccount = config.list.accountset[i].account.ToString();

                        }
                    }
                }
                else
                {
                    MessageBox.Show("参数有错误,请通知su112wei");
                    this.Close();
                }

                
            }
            else
            {
                for (int i = 0; i < config.list.accountset.Count; i++)
                {
                    if (config.list.accountset[i].account.account.Length > 0)
                    {
                        System.Diagnostics.Debug.WriteLine(config.list.accountset[i].account.account);
                        Process.Start("SpyTxT.exe", config.list.accountset[i].account.account);
                       

                    }
                    else
                    {
                        MessageBox.Show("启动参数有误,请检查");
                        this.Close();
                    }
                }
                MessageBox.Show("启动成功");
                this.Close();
                Environment.Exit(0);
                
            }
            //if (!ReadConfig())
            //{
            //    MessageBox.Show("config no right!");
            //    this.Close();
            //}  

            FileStream file1 = new FileStream("citylist.xml", FileMode.Open);

            StreamReader ms1 = new StreamReader(file1, Encoding.Default);


            try
            {
                XmlSerializer objSerializer = new XmlSerializer(typeof(rootmylist));

               rootmylist = (rootmylist)objSerializer.Deserialize(ms1);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            file1.Close();

            ms1.Close();

            foreach (AreaCityList a in this.rootmylist.rootlist.list)
            {
               arealisttree.Add(a);
            }

            this.treeView1.ItemsSource = arealisttree;

             
            NewDebugItem();
            NewTabItem(guoliannet.Selectcity);
           

            if (this.getConfig().list.bautostart == "1")
            {
                if (guoliannet.Computerkey != "" && guoliannet.Loginusername != "" && guoliannet.Loginpassword != "")
                    guoliannet.init();
                else
                {
                    
                    MessageBox.Show("must import account!");
                    this.Close();
                }
                   

                dTimer.Tick += new EventHandler(RunStateTick);
                dTimer.Interval = new TimeSpan(0, 0, 1);
                dTimer.Start();
            }

            //this.Title = this.getConfig().list.login;
            this.Title = guoliannet.Loginaccount;
            //this.SelectCity("北京");


        }

        //////////////////////////可以外部调用的接口实现////////////////////////////////////////////////

        /// <summary>
        /// 加入解密后的XML数据
        /// </summary>
        /// <param name="xmldata"></param>
        public void AddRevXMLData(string xmldata)
        {
            doxmlmanger.AddXMLData(xmldata);
        }
        /// <summary>
        /// 保存登陆的ID字符串
        /// </summary>
        /// <param name="ticket"></param>
        public void SetTicket(string ticket)
        {
            ticketbylogin = ticket;
        }
        /// <summary>
        /// 获取登陆ID字符串
        /// </summary>
        /// <returns></returns>
        public string GetTicket()
        {
            return ticketbylogin;
        }
        /// <summary>
        /// 设置当前运行状态
        /// </summary>
        /// <param name="state"></param>
        public void SetState(StateManager.STATE_MODE state)
        {
            statemanager.SetState(state);
        }
        /// <summary>
        /// 删除一个处理回调
        /// </summary>
        /// <param name="p"></param>
        public void DeleteDoXML(IDoXML p)
        {
            doxmlmanger.DeleteXML(p);
        }
        /// <summary>
        /// 开始获取登陆ID字符串
        /// </summary>
        public void LoginGetTicket()
        {
            statemanager.AddStateImp(StateManager.STATE_MODE.STATE_LOGIN_TICKET, dogetloginticketxml);
            doxmlmanger.AddDoXML(dogetloginticketxml);
            getloginticket.Login1();

        }
        /// <summary>
        /// 登陆进入天下通
        /// </summary>
        public void LoginIntoTXT()
        {
            statemanager.AddStateImp(StateManager.STATE_MODE.STATE_LOGIN_TXT, dogettxtxml);
            doxmlmanger.AddDoXML(dogettxtxml);
            getloginticket.Login2();
        }

        /// <summary>
        /// 开始软件更新
        /// </summary>
        public void SoftInfUpdata()
        {
            statemanager.AddStateImp(StateManager.STATE_MODE.STATE_LOGIN_UPDATA, dosoftinfupdataxml);
            doxmlmanger.AddDoXML(dosoftinfupdataxml);
            softinfupdatanet.init();
        }

        /// <summary>
        /// 根据城市名字设置数据源
        /// </summary>
        /// <param name="temple"></param>
        public void SetListBoxSourceByName(string cityname)
        {
            //this.listbox.ItemsSource = citypeihuomanager.GetPeiHuoByCity(this.selectcityname);
        }

        /// <summary>
        /// 加入配货信息
        /// </summary>
        /// <param name="peihuotemple"></param>
        public void AddPeiHuoTemple(PeiHuoTemple p)
        {
            if(this.selectcityname !=null)
               citypeihuomanager.AddPeiHuo(p, this.selectcityname);


        }



        /// <summary>
        /// 设置选择的城市
        /// 
        /// </summary>
        /// <param name="cityname"></param>
        public void SelectCity(string cityname)
        {
            this.selectcityname = cityname;
        }


        /// <summary>
        /// 得到选择的城市
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetSelectCity()
        {
            return this.selectcityname;
        }

        /// <summary>
        /// 得到当前城市数据源里面最后尾ID
        /// </summary>
        /// <returns></returns>
        public string GetCurSelectAreaCityMaxid()
        {
            PeiHuoListTemple list = citypeihuomanager.GetPeiHuoByCity(this.GetSelectCity());

            if (list != null)
            {
                return list[list.Count - 1].id;
            }

            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetCurSelectAreaCityFristRow()
        {

            return citypeihuomanager.GetCurLookInfroRow(GetSelectCity());

        }

        /// <summary>
        /// 
        /// </summary>
        public void SetCurSelectAreaCityFristRow(string firstrow)
        {
            citypeihuomanager.SetCurLookInfroRow(this.GetSelectCity(), firstrow);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="maxcount"></param>
        public void SetCurInfroMaxCount(string maxcount)
        {
            citypeihuomanager.SetMaxCountInfroByCity(maxcount, GetSelectCity());
        }

        public string GetCurInfroMaxCount()
        {
            return citypeihuomanager.GetMaxCountInfroByCity(this.GetSelectCity());
        }

        public void SetLogin(Boolean b)
        {
            this.bLoginOk = b;
        }

        public Boolean GetLogin()
        {
            return this.bLoginOk;
        }

        public void AddDebugInfo(string debuginfo)
        {
            DebugInfoTemple d = new DebugInfoTemple();
            d.debuginfo = debuginfo;
            this.debuginfolist.Insert(0, d);
        }

        public void SetRunInfo(string info)
        {
            tbox.Text = info;
        }

        public void SelectListenCity(String cityname)
        {
            if (cityname != "")
            {

                this.SelectCity(cityname);

                if (this.GetLogin())
                    getloginticket.SelectCity(this.GetSelectCity());

                NewTabItem(cityname);

                this.guoliannet.ClickCity(cityname);
                this.guoliannet.CityId = this.rootmylist.findcityIdbyName(cityname);
            }
        }

        public Config getConfig()
        {
            return config;
        }

        //////////////////////////////////////////////////////////////////////////

        protected void OnClosed(object sender, System.EventArgs e)
        {
            checknet.Close();
            getloginticket.Close();
            softinfupdatanet.Close();
            guoliannet.Close();

            
            dTimer.Stop();

        }
        private void QuitClicked(object sender, RoutedEventArgs e)
        {

        }

        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {

        }

        private void Expander_Expanded_1(object sender, RoutedEventArgs e)
        {

        }
        public void NewDebugItem()
        {
            TabItem tb = new TabItem();

            tb.Header = "信息";

            ListBox listbox = new ListBox();

            listbox.ItemsSource = debuginfolist;
            listbox.ItemContainerStyle = (Style)this.Resources["ListBoxItemStyle2"];
            tb.Content = listbox;


            this.tabControl1.Items.Add(tb);

            this.tabControl1.SelectedItem = tb;

            TabItem tb2 = new TabItem();
           

            tb2.Header = "运行";
            tb2.Content = tbox;
            tbox.TextWrapping = TextWrapping.Wrap;
            tbox.AcceptsReturn = true;
            tbox.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;

            this.tabControl1.Items.Add(tb2);




        }
        public void NewTabItem(string areacity)
        {
            foreach (TabItem b in this.tabControl1.Items)
            {
                if (b.Header.Equals(areacity))
                {
                    this.tabControl1.SelectedItem = b;
                    return;
                }
            }

            TabItem tb = new TabItem();

            tb.Header = areacity;

            ListBox listbox = new ListBox();

            listbox.ItemsSource = this.citypeihuomanager.GetPeiHuoByCity(areacity);
            //listbox.ItemContainerStyle = (Style)this.Resources["ListBoxItemStyle1"];
            tb.Content = listbox;

            this.tabControl1.Items.Add(tb);

            this.tabControl1.SelectedItem = tb;


        }
        public void SelectionChanged(object sender, RoutedPropertyChangedEventArgs<Object> e)
        {
            City a = e.NewValue as City;
            if (a != null)
            {

                this.SelectCity(a.name);

                if (this.GetLogin())
                    getloginticket.SelectCity(this.GetSelectCity());

                NewTabItem(a.name);

                this.guoliannet.ClickCity(a.name);
                this.guoliannet.CityId = this.rootmylist.findcityIdbyName(a.name);
            }

        }
        private void treeview_MouseDown(object sender, RoutedEventArgs e)
        {

        }
        private void tabcontrol_selectchanged(object sender, SelectionChangedEventArgs args)
        {
           
        }



        private void button1_Click1(object sender, RoutedEventArgs e)
        {
            
            //byte[] ddd = { 0x31, 0x32, 0x33, 0x34, 0x35};

            //String d1 = Encoding.Default.GetString(ddd);
            //System.Console.WriteLine(d1);
                //Int32 ddd = Int32.Parse(config.list.bchangelistencitytime);

                //tbox.Text = ddd.ToString() ;
                ////getloginticket.GetNextPageInfro();
                //AddDebugInfo("1111111111");
                //HttpCommit.Post("beijing", "guangzhou", "haha", "1111111", "22222222222");
                //String cookie = HttpCommit.GetTheirServer();
                //if (cookie != "")
            //String d2 = "有6.8米东风高栏车长期承接潍坊寒亭坊子的小件物流大件配送业务 寻找长期客户 电 电话:13466369078";
            //System.Console.WriteLine(d2);
            //HttpCommit.PostTheirServer("山东", "潍坊", "潍坊", "潍坊", "潍坊", "潍坊", "转让一部9.6米后八轮平板车 车况良好18吨行驶证联系189;544;63866; 电话:88888","test", "test", "1234567");

          
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //guoliannet.Computerkey = "9QG2CNZV";
            //guoliannet.Loginusername = "1617";
            //guoliannet.Loginpassword = "1617";

            if (guoliannet.Computerkey != "" && guoliannet.Loginusername != "" && guoliannet.Loginpassword != "")
                guoliannet.init();
            else
                MessageBox.Show("must import account!");

            //qqlogin.GetQQPictureData("111111111");
            //             if (peihuo != null)
            //             {
            //                 foreach (PeiHuoTemple p in peihuo.peihuodata._peihuolist)
            //                 {
            // 
            //                     System.Diagnostics.Debug.WriteLine(p.postcity);
            //                 }
            //                 
            //             }
            //             PeiHuoTemple p = new PeiHuoTemple();
            //             string dd = "哈哈哈哈哈";
            //             p.content = dd;
            //             p.fromcity = "北京";
            //              
            //             AddPeiHuoTemple(p);




            //                 PeiHuoListTemple p = new PeiHuoListTemple();
            //                 p.Add(new PeiHuoTemple("1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"));
            //                 p.Add(new PeiHuoTemple("22222", "133333", "14444444", "15555", "144444", "1", "1", "3333331", "1", "1", "1", "1", "1"));
            //                 this.listbox.ItemsSource = p;
            //             checknet.init();
            // 
           
                dTimer.Tick += new EventHandler(RunStateTick);
                dTimer.Interval = new TimeSpan(0, 0, 1);
                dTimer.Start();
           
           
            //             this.button1.IsEnabled = false;

            //             statemanager.SetState(StateManager.STATE_MODE.STATE_CHECK_NET);
            // 
            //             statemanager.SetState(StateManager.STATE_MODE.STATE_CHECK_NET);


            //             byte[] data ={0x03,0x89,0x55,0xef,0x65,0x5b,0xca,0x34,0x10,0xb1,0x62,0x08,0xc1,0xd8,0x83,0x78};
            //             
            //             byte[] result;
            // 
            //             MD5 md5 = MD5.Create();
            //             string pass = "abcd1234567";
            //             byte[] md5data = md5.ComputeHash(Encoding.Default.GetBytes(pass));
            //             md5data = md5.ComputeHash(md5data);
            // 
            //             string base64 = Convert.ToBase64String(md5data);
            // 
            //             md5data = Encoding.Default.GetBytes(base64);

            //001262DC  D3 E0 8E BA CD 13 50 EA 73 D1 EF 53 5F 5C 6B EA  余幒?P阺扬S_\k







        }
        private void RunStateTick(object sender, EventArgs e)
        {
            doxmlmanger.DoXMLRun();
            statemanager.RunState();

        }


        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void MouseClickButtonStoryboard(object sender, SelectionChangedEventArgs e)
        {

        }

        private void OnClickLabel(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            System.Console.WriteLine("111111111111111");
        }
        private bool ReadConfig()
        {
            
            FileStream file = new FileStream("spytxtsetting.xml", FileMode.Open);

            StreamReader ms = new StreamReader(file, Encoding.Default);


            try
            {
                XmlSerializer objSerializer = new XmlSerializer(typeof(Config));

                config = (Config)objSerializer.Deserialize(ms);
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            //if (config != null)
            //{
            //    guoliannet.OnLoad(config);
            //    return true;
            //}

            file.Close();

            ms.Close();

            return true;
        }
        public void ImportAccount(object sender, RoutedEventArgs e)
        {

            ReadConfig();

        }




    }
        

    class GetQQPictureNet : UIAction, IInitUIAction, IDoPack
    {
        private NetClient qqlogin = new NetClient();
        private FileStream picture = null;
        public void IDoPackData(Byte[] data, int len)
        {
            picture.Write(data, 0,data.Length);
        }
        
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);
        }

        public void GetQQPictureData(string qq)
        {
            UInt32 qqdata = Convert.ToUInt32(qq);


            picture = new FileStream("C:\\qqloginpicture.jpeg", FileMode.OpenOrCreate);

            byte[] data = {0x02,0x00,0x0E,0x01,0x01,0x00,0x01,0x00,0x2A,0x3E,0xC6,0x03,0xF1,0x03};

            qqlogin.InitNet("58.60.9.61",443,NetClient.NetMode.TCP_CLIENT);
            qqlogin.Idopack = this;
        
            qqlogin.ClientSend(data);
            
        }

    }
    class GetLoginTicketNet : UIAction, IInitUIAction, IDoPack
    {
        private NetClient login1 = new NetClient();
        private DoNetData donetdata = new DoNetData();
        private PackManger pack = new PackManger();
        
        public GetLoginTicketNet()
        {
            
        }
        public void Close()
        {
            login1.CloseClient();
        }
        public void InitUIAction(IUIAction p)
        {
            donetdata.SetUIAction(p);
            this.SetUIAction(p);
        }
        public void IDoPackData(Byte[] data, int len)
        {
            donetdata.DoXmlData(data);
        }
        public void Login1()
        {
            // 体验登陆
            //string result = pack.IniLoginInTo("txtest", "123456");

            string result = pack.IniLoginInTo("maijjj", "111111");

            

            login1.InitNet("123.130.126.79", 996, NetClient.NetMode.TCP_CLIENT);
            login1.Idopack = this;
            login1.ClientSend(result);
        }
        public void Login2()
        {
            //pack.SetCryptKey("9QG2CNZV#005056C00008", ticket);
            //pack.SetCryptKey("9RA4VRAS#005056C00008", ticket);

            donetdata.bLog = true;
            donetdata.SetCryptKey(pack.GetMachineno(), this.GetUIAction().GetTicket());

            string result = pack.InitLoginCmd10(this.GetUIAction().GetTicket());

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd93();

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd23();

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd60();

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd41("北京");

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd42("北京");

            login1.ClientSend(result);

            
            result = pack.InitLoginCmd34(this.GetUIAction().GetTicket());

            login1.ClientSend(result);

            
            result = pack.InitLoginCmd99("北京");

            login1.ClientSend(result);

            
            result = pack.InitLoginCmd94(this.GetUIAction().GetTicket());

            login1.ClientSend(result);

            
            result = pack.InitLoginCmd23();

            login1.ClientSend(result);

            

            result = pack.InitLoginCmd34(this.GetUIAction().GetTicket());

            login1.ClientSend(result);


            Thread.Sleep(1000);

            SelectCity("北京");
        }

        public void SelectCity(string cityname)
        {
            string result = pack.InitLoginCmd27(cityname);

            login1.ClientSend(result);



            result = pack.IniiRequestCityLogin(cityname);

            login1.ClientSend(result);


        }

        public void GetNextPageInfro()
        {
            string maxid = this.GetUIAction().GetCurSelectAreaCityMaxid();
            string count = this.GetUIAction().GetCurSelectAreaCityFristRow();
            
            if (count == null)
            {
                count = this.GetUIAction().GetCurInfroMaxCount();
                this.GetUIAction().SetCurSelectAreaCityFristRow(count);
            }
            int icount = Convert.ToInt32(count);
            icount = icount - 20;
            if (icount > 0)
            {
                count = Convert.ToString(icount);
                string result = pack.GetOldPeiHuoInfro(count, maxid);

                login1.ClientSend(result);
            }
            


        }
    }
    class DoGetLoginTicketXML : UIAction,IInitUIAction,IDoXML, IState
    {
        private PackManger pack = new PackManger();

        public DoGetLoginTicketXML()
        {
            
        }
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);
        }
        public void Run()
        {
            
        }
        public Boolean DoXML(string xmldata)
        {
            int pos1 = xmldata.IndexOf("<ticket>");
            int pos2 = xmldata.IndexOf("</ticket>");
            if (pos1 != -1 && pos2 != -1 && pos2 > pos1)
            {
                string ticket = xmldata.Substring(pos1 + 8, pos2 - pos1 - 8);


                System.Diagnostics.Debug.WriteLine("获取临时ID成功.");

                this.GetUIAction().SetTicket(ticket);

                this.GetUIAction().DeleteDoXML(this);

                this.GetUIAction().SoftInfUpdata();
// 


                return true;

            }
            if (xmldata.LastIndexOf("<end/>") != -1)
            {
                return false;

            }

            return false;
        }
    }
    class DoGetTXTXML : UIAction, IInitUIAction, IDoXML, IState
    {
        private PackManger pack = new PackManger();

        public DoGetTXTXML()
        {

        }
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);
        }
        public void Run()
        {

        }
        public Boolean DoXML(string xmldata)
        {
            System.Diagnostics.Debug.WriteLine(xmldata);
            commblock obj = pack.XmlSerializertObj(xmldata);

            if (obj != null)
            {
                if(obj.command == "21" || obj.command == "22")
                {
                    this.GetUIAction().SetLogin(true);

                    foreach (PeiHuoTemple p in obj.peihuodata._peihuolist)
                    {
                        this.GetUIAction().AddPeiHuoTemple(p);
                    }
                    this.GetUIAction().SetListBoxSourceByName(this.GetUIAction().GetSelectCity());

                    if(obj.peihuodata.count != null)
                        this.GetUIAction().SetCurInfroMaxCount(obj.peihuodata.count);

                    if (obj.peihuodata.firstrow != null)
                    {
                        this.GetUIAction().SetCurSelectAreaCityFristRow(obj.peihuodata.firstrow);
                    }
                    
                }
                
            }

            return false;
        }
    }
    class SoftInfUpdataNet :UIAction,IDoPack,IInitUIAction
    {
        private NetClient httpinfo = new NetClient();
        private NetClient httpinfo1 = new NetClient();
        private NetClient login3 = new NetClient();
        private DoNetData donetdata = new DoNetData();
        private PackManger pack = new PackManger();
        

        public SoftInfUpdataNet()
        {
            
        }
        public void Close()
        {
            httpinfo.CloseClient();
            httpinfo1.CloseClient();
            login3.CloseClient();
        }
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);
            donetdata.SetUIAction(p);

        }
        public void IDoPackData(Byte[] data, int len)
        {
            donetdata.DoXmlData(data);
        }
        public void init()
        {
            System.Diagnostics.Debug.WriteLine("开始获取软件更新.");
//             httpinfo.InitNet("123.130.126.79", 80, this, NetClient.NetMode.TCP_CLIENT);
// 
//             httpinfo1.InitNet("123.130.126.72", 80, this, NetClient.NetMode.TCP_CLIENT);

            login3.InitNet("123.130.126.79", 996, NetClient.NetMode.TCP_CLIENT);
            login3.Idopack = this;
            string result = pack.InitLogin2(); // 获取软件背景颜色等配置

            login3.ClientSend(result);

        }

    }
    //
    class DoSoftInfUpdataXML : UIAction,IInitUIAction,IDoXML,IState
    {
        public void Run()
        {

        }
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);

        }
        public Boolean DoXML(string xmldata)
        {
            if (xmldata.LastIndexOf("<end/>") != -1)
            {

                this.GetUIAction().DeleteDoXML(this);
                this.GetUIAction().LoginIntoTXT();
                System.Diagnostics.Debug.WriteLine("登陆天下通.");
                this.GetUIAction().SelectCity("北京");

                return true;    
            }

            return false;
            
        }
    }
    class PostThreadImp
    {
        private String posturl;
        private GuoLianNet guolian;
        private ArrayList postlist = new ArrayList();
        private bool bstart = true;
        public PostThreadImp(String url,GuoLianNet g)
        {
            this.posturl = url;
            guolian = g;
        }
        public void PostThread()
        {
            while (bstart)
            {
                Monitor.Enter(postlist);

                ArrayList copy = (ArrayList)postlist.Clone();
                postlist.Clear();
                Monitor.Exit(postlist);
                if (copy.Count > 0)
                {

                    foreach (PeiHuoTemple p in copy)
                    {
                       
                        String postdata = "";
                        if (posturl.IndexOf("su112wei.vicp.net") != -1)
                        {
                            guolian.PostMy1++;
                            postdata = "tocity=" + guolian.CityId + "&fromcity=" + "" + "&contact=" + "" + "&tel=" + p.innerphone + "&content=" + p.content;

                        }
                        else if (posturl.IndexOf("test.ny-dt.com") != -1)
                        {
                            guolian.PostOther1++;

                            postdata += "wlrData.type=%E8%B4%A7%E6%BA%90";
                            postdata += "&wlrData.startProvince=" + "山东";
                            postdata += "&wlrData.startCity=" + guolian.Selectcity;
                            postdata += "&wlrData.startRegion=" + guolian.Selectcity;
                            postdata += "&wlrData.endProvince=" + "test";
                            postdata += "&wlrData.endCity=" + "test";
                            postdata += "&wlrData.endRegion=" + "test";
                            postdata += "&wlrData.content=" + p.content;
                            postdata += "&wlrData.time=" + DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss");
                            postdata += "&wlrData.contact=" + "test";

                            postdata += "&wlrData.phone=" + p.innerphone;


                        }

                        HttpCommit.PostTo(posturl, postdata);
                    }
                }
                

                Thread.Sleep(100);
            }
        }
        public void Stop()
        {
            bstart = false;        
        }

        public void AddWuliuInfo(ArrayList info)
        {
            Monitor.Enter(postlist);

            postlist.AddRange(info);
            Monitor.Exit(postlist);
        }
    }
    /// <summary>
    /// 国联物流登陆
    /// </summary>
    class GuoLianNet : UIAction, IInitUIAction, IDoPack, IState, INetError, IConfig
    {
        private NetClient login = new NetClient();
        private GuoLianPackManger pack = new GuoLianPackManger();
        
        private DoNetData donetdata = new DoNetData();
        private int sendstate = 0;
        private ArrayList wuliuinfo = new ArrayList();
        private ArrayList postwuliuinfo = new ArrayList();
        private ArrayList debuginfo = new ArrayList();
        private ArrayList postthread = new ArrayList();
        
        private int allcount = 0;// 全国所有信息数量
        private int curcitycount = 0;//当前城市信息数量
        public int reconnecttime = 0;//重连时间
        public int runstate = 0;// 运行状态
        public int msgindex = 13;//基数
        public long getmsgtime = 0;

        private string loginusername = "";
        private string loginpassword = "";
        private string computerkey = "";

        private DateTime senddatatime1;
        private DateTime senddatatime2;
        // 记录post次数
        private int PostMy = 0;

        public int PostMy1
        {
            get { return PostMy; }
            set { PostMy = value; }
        }
        private int PostOther = 0;

        public int PostOther1
        {
            get { return PostOther; }
            set { PostOther = value; }
        }
        // 切换城市监听时间
        private DateTime changecitytime = DateTime.Now;

        private int changelistencity = 0;
        // 用于登录后选择监听城市
        private bool bInitConfig = true;
        private DateTime logininitime = DateTime.Now;

        private int[] Port = { 20415, 20416, 27262, 20417, 20418, 20415, 20420, 20421, 20422, 20423, 20424 };
        private int indexport = 0;
        public string Loginusername
        {
            get { return loginusername; }
            set { loginusername = value; }
        }

        public string Loginpassword
        {
            get { return loginpassword; }
            set { loginpassword = value; }
        }

        public string Computerkey
        {
            get { return computerkey; }
            set { computerkey = value; }
        }

        public long Getmsgtime
        {
            get { return getmsgtime; }
            set { getmsgtime = value; }
        }
        public int Msgindex
        {
            get { return msgindex; }
            set { msgindex = value; }
        }
        public int Runstate
        {
            get { return runstate; }
            set { runstate = value; }
        }
        public int Reconnecttime
        {
            get { return reconnecttime; }
            set { reconnecttime = value; }
        }
        public int Sendstate
        {
            get { return sendstate; }
            set { sendstate = value; }
        }
        public SpyTxT.GuoLianPackManger Pack
        {
            get { return pack; }
            set { pack = value; }
        }

        // 接收信息数量
        private int msgcount = 0;

        private bool brestart = true;

        public int Msgcount
        {
            get { return msgcount; }
            set { msgcount = value; }
        }
        // 开始运行时间
        private DateTime starttime = DateTime.Now;
        // 最后接收信息时间
        private DateTime lastrecvtime = DateTime.Now;

        public DateTime Lastrecvtime
        {
            get { return lastrecvtime; }
            set { lastrecvtime = value; }
        }
        // 登录次数
        private int logincount = 0;

        public int Logincount
        {
            get { return logincount; }
            set { logincount = value; }
        }
        // 登录帐号
        private string loginaccount;

        public string Loginaccount
        {
            get { return loginaccount; }
            set { loginaccount = value; }
        }
        // 当前选择城市
        private string selectcity;

        public string Selectcity
        {
            get { return selectcity; }
            set { selectcity = value; }
        }
        private string cityId = "";

        public string CityId
        {
            get { return cityId; }
            set { cityId = value; }
        }

        // 上传信息次数
        private int postinfoservercount;

        public int Postinfoservercount
        {
            get { return postinfoservercount; }
            set { postinfoservercount = value; }
        }
        // 成功上传信息次数
        private int postinfoserverokcount;

        public int Postinfoserverokcount
        {
            get { return postinfoserverokcount; }
            set { postinfoserverokcount = value; }
        }

        private int recvdatalen = 0;

        public int Recvdatalen
        {
            get { return recvdatalen; }
            set { recvdatalen = value; }
        }
        public GuoLianNet ()
        {

        }
      
        // 读取配置接口
        public void OnLoad(Config config)
        {
            for (int i = 0; i < config.list.accountset.Count; i++)
            {
                if (config.list.accountset[i].account.account == config.list.login)
                {
                    this.Computerkey = config.list.accountset[i].computerkey.ToString();
                    this.Loginusername = config.list.accountset[i].account.ToString();
                    this.Loginpassword = config.list.accountset[i].password.ToString();
                    this.Selectcity = config.list.accountset[i].listencity.initcity;
                    this.Loginaccount = config.list.accountset[i].account.ToString();

                }
            }
        }
        public void OnSave(Config config)
        { 
            
        }
        public void Close()
        {
            login.CloseClient();

            foreach (PostThreadImp p in postthread)
            {
                p.Stop();
                Thread.Sleep(1000);
            }

        }
        public void AddDebugInfo(string info)
        {
            //Monitor.Enter(debuginfo);

            info = DateTime.Now.ToString("F") + " " + info;
            debuginfo.Add(info);
           
           // Monitor.Exit(debuginfo);

            System.Console.WriteLine(info);
        }

        // 过滤信息
        public bool FilterInfo(String content)
        {
            Config config = this.GetUIAction().getConfig();

            if (config.filterele.benable == "1")
            {
                String[] filter = config.filterele.filter.Split(';');

                foreach (String a in filter)
                {
                    if (a != "" && content.IndexOf(a) != -1)
                    {
                        AddDebugInfo("过滤:" + content);

                        return true;
                    }
                }
            }
            

            return false;


        }

        public void ShowRunInfo()
        {
            Config config = this.GetUIAction().getConfig();


            ////////////////////////////////////////////////////////////////////

            String info = "";
            info += "接收信息数量:" + this.Msgcount + "(条)" + "\n";
            info += "软件启动时间:" + starttime.ToString("F") + "\n";
            info += "最新接收时间:" + lastrecvtime.ToString("F") + "\n";
            info += "总共登录次数:" + this.Logincount + "(次)" + "\n";
            info += "登录帐号名字:" + this.Loginaccount + "\n";
            info += "当前选中城市:" + this.Selectcity + "\n";
            info += "上传信息次数:" + this.postinfoservercount + "(次)" + "\n";
            info += "成功信息次数:" + this.postinfoserverokcount + "(次)" + "\n";
            info += "是否循环监听:" + config.list.blooplistencity + "\n";
            info += "切换监听时间:" + config.list.bchangelistencitytime + "(分钟)" + "\n";
            info += "定时重新登录:" + config.list.restarttime + "(点)" + "\n";
            info += "上次切换时间:" + changecitytime.ToString("F") + "\n";
            if (config.list.blooplistencity == "1")
                info += "距离切换时间:" + (DateTime.Now - changecitytime).TotalSeconds + "(s)" + "\n";
            info += "是否过滤信息:" + config.filterele.benable + "\n";
            info += "过滤关键信息:" + config.filterele.filter + "\n";
            info += "接收线程时间:" + login.Runrecvtime.ToString("F") + "\n";
            info += "发送线程时间:" + login.Runsendtime.ToString("F") + "\n";
            info += "POST_MY:" + PostMy + "\n";
            info += "POST_Otheir:" + PostOther + "\n";
            info += "接收数据长度:" + recvdatalen + "\n";
            this.GetUIAction().SetRunInfo(info);
        
        }
        // 主线程定时器回调
        public void Run()
        {
            Config config = this.GetUIAction().getConfig();

            ShowRunInfo();

            ////////////////////////////////////////////////////////////////////
           

            // 定时重新登录
            if (DateTime.Now.Hour == Int32.Parse(config.list.restarttime) && brestart)
            {
                for (int i = 0; i < config.list.accountset.Count; i++)
                {
                    if (config.list.accountset[i].account.account == this.Loginusername)
                    {
                        this.Selectcity = config.list.accountset[i].listencity.initcity;
                    }
                }
                AddDebugInfo("定时重新登录");
                brestart = false;
                login.CloseClient();
                this.init();

                return;

            }
            if (DateTime.Now.Hour ==  (Int32.Parse(config.list.restarttime) + 1))
                brestart = true;
            ////////////////////////////////////////////////////////////////////
            // 轮询监听城市
            TimeSpan sp = DateTime.Now - Lastrecvtime;

            if(sp.TotalMinutes > Int32.Parse(config.list.recvouttime))
            {
                AddDebugInfo("接收超时,重新登录.");
                Lastrecvtime = DateTime.Now;
                login.CloseClient();
                this.init();

                return;
            }

            ////////////////////////////////////////////////////////////////////

            if ((DateTime.Now - senddatatime1).TotalSeconds > 60)
            {
                System.Console.WriteLine("SEND time data 1");
                senddatatime1 = DateTime.Now;

                Byte[] data = pack.InitTimeDate(this.Loginaccount);
                Byte[] sendbuf = (Byte[])data.Clone();
                login.ClientSend(sendbuf);
                
                return;
            }

            if ((DateTime.Now - senddatatime2).TotalSeconds > 70)
            {
                senddatatime2 = DateTime.Now;
                System.Console.WriteLine("SEND time data 2");
                Byte[] data = pack.InitTimeDate2();
                Byte[] sendbuf = (Byte[])data.Clone();
                login.ClientSend(sendbuf);
                
                return;
            }


            ////////////////////////////////////////////////////////////////////
            

            bool bchangelisten = false;
            TimeSpan sptime = DateTime.Now - changecitytime;

            if (config.list.blooplistencity == "1" && sptime.TotalMinutes > Int32.Parse(config.list.bchangelistencitytime))
            {
                changecitytime = DateTime.Now;
                bchangelisten = true;
            }

            if (bchangelisten)
            {
                for (int i = 0; i < config.list.accountset.Count; i++)
                {
                    if (config.list.accountset[i].account.account == this.Loginusername)
                    {
                        if (config.list.accountset[i].listencity.citylist.Count > 0 && changelistencity < config.list.accountset[i].listencity.citylist.Count)
                        {
                            if (config.list.accountset[i].listencity.citylist[changelistencity].city != this.Selectcity)
                            {
                                
                                AddDebugInfo("切换监听城市:" + config.list.accountset[i].listencity.citylist[changelistencity].city);
   
                                this.GetUIAction().SelectListenCity(config.list.accountset[i].listencity.citylist[changelistencity].city);
                            }
                            changelistencity++;

                        }
                        else
                        {
                            changelistencity = 0;
                        }


                    }
                }
            }

           

            ////////////////////////////////////////////////////////////////////
            // 显示调试信息
            if (debuginfo.Count > 0)
            {
                try
                {
                    Monitor.Enter(debuginfo);

                    for (int i = 0; i < debuginfo.Count; i++)
                    {
                        Monitor.Enter(debuginfo);
                        String p = (String)debuginfo[i];
                        this.GetUIAction().AddDebugInfo(p);
                    }

                    Monitor.Exit(debuginfo);

                }
                finally
                {

                    debuginfo.Clear();

                    Monitor.Exit(debuginfo);
                }
               
            }

            
            ////////////////////////////////////////////////////////////////////
            // 显示物流信息
            if (wuliuinfo.Count > 0)
            {
                FileStream f = null;
                try
                {
   
                    // 过滤信息
                    Monitor.Enter(wuliuinfo);
                    for (int i = 0; i < wuliuinfo.Count; i++)
                    { 
                         PeiHuoTemple p = (PeiHuoTemple)wuliuinfo[i];
                         if (p != null && FilterInfo(p.content))
                             wuliuinfo.Remove(p);
                    }
                    
                    ArrayList copy = (ArrayList)wuliuinfo.Clone();
                    wuliuinfo.Clear();
                    Monitor.Exit(wuliuinfo);

                    // 只能addRange 拷贝过去,不能Clone() 会破坏原先对象
                    foreach (PostThreadImp p in postthread)
                    {
                        p.AddWuliuInfo(copy);
                    }


                    this.Msgcount += copy.Count;
                    this.lastrecvtime = DateTime.Now;
                    this.postinfoservercount += copy.Count;

                    f = File.Open("c:\\data1.txt", FileMode.Append);
                    f.Seek(0, SeekOrigin.End);
                    for (int i = 0; i < copy.Count; i++)
                    {
                        PeiHuoTemple p = (PeiHuoTemple)copy[i];

                        String data = p.content + "\n";

                        Byte[] textdata = Encoding.Default.GetBytes(data);
                        f.Write(textdata, 0, textdata.Length);


                        // 过滤信息
                        if (FilterInfo(p.content))
                            continue;

                        this.GetUIAction().AddPeiHuoTemple(p);
                    }

                    f.Close();
                }
                catch (System.Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    if (f != null)
                        f.Close();
                  
                }
                
                //this.Runstate = 1;

               
              

            }
            else if (Recvdatalen == 0 && (DateTime.Now - lastrecvtime).TotalSeconds > 30)
            {
                lastrecvtime = DateTime.Now;
                this.Sendstate = 2;
                indexport++;
                AddDebugInfo("登录后接收超时");
            }
            
            if (this.bInitConfig && this.login.IsConnect() && this.Selectcity != "" && (DateTime.Now - logininitime).TotalMinutes > 1)
            {
                this.bInitConfig = false;
                AddDebugInfo("登录后选择:" + this.Selectcity);
                this.GetUIAction().SelectListenCity(this.Selectcity);
            }

            if (this.Sendstate == 2 && System.Environment.TickCount - this.Reconnecttime > 10000)
            {
                
                this.Reconnecttime = System.Environment.TickCount;
                AddDebugInfo("重新连接.");
                login.CloseClient();
                this.init();
                
            }

            if (this.Runstate == 1 && System.Environment.TickCount - this.Getmsgtime > 2000)
            {
                this.Getmsgtime = System.Environment.TickCount;

                if (this.curcitycount > this.Msgindex)
                {
                    Byte[] packdata = pack.getOldMsgPack(this.Msgindex);

                    Byte[] sendbuf = new Byte[packdata.Length];
                    Array.Copy(packdata, 0, sendbuf, 0, packdata.Length);

                    login.ClientSend(sendbuf);

                    this.Msgindex += 0x12;

                    System.Console.WriteLine("当前城市信息总数:");
                    System.Console.WriteLine(curcitycount);
                    System.Console.WriteLine("\n");
                    System.Console.WriteLine("信息序号:");
                    System.Console.WriteLine(this.Msgindex);
                    System.Console.WriteLine("\n");

                }
                else
                {
                    this.Runstate = 0;
                    System.Console.WriteLine("获取当日的信息 完毕");
                }
            }
        }

        public void ClickCity(String city)
        {
            this.Selectcity = city;
            Byte[] clickcitydata = pack.GetWuliuByCity(city);

            Byte[] sendbuf = new Byte[clickcitydata.Length];
            Array.Copy(clickcitydata, 0, sendbuf, 0, clickcitydata.Length);

            login.ClientSend(sendbuf);

        }
       
        public void init()
        {
            if (postthread.Count == 0)
            {
                Config config = this.GetUIAction().getConfig();
                if(config.postset.benable == "1")
                {
                    for (int d = 0; d < config.postset.accountset.Count; d++)
                    {
                        if(config.postset.accountset[d].benable == "1")
                        {
                            PostThreadImp p1 = new PostThreadImp(config.postset.accountset[d].posturl,this);
                            Thread t1 = new Thread(new ThreadStart(p1.PostThread));
                            t1.Start();
                            postthread.Add(p1);
                         }
                    }
                
                
                }
                

            }
            //int buflen1 = 0;
            //Byte[] packbuf1 = pack.InitLoginPack2("1617", "1617", "9QG2CNZV", ref buflen1);
            //Byte[] sendbuf1 = new Byte[buflen1];
            //Array.Copy(packbuf1, 0, sendbuf1, 0, buflen1);
            //this.Loginaccount = "1617";
            login.Ineterror = this;
            login.Idopack = this;

           if (!login.IsConnect())
           {

               AddDebugInfo("初始化网络");
               int ConnectPort = 20415;
               if (indexport >= Port.Length)
                   indexport = 0;

               ConnectPort = Port[indexport];

               if (login.InitNet("203.171.239.51", ConnectPort, NetClient.NetMode.TCP_CLIENT))
               {
                   senddatatime1 = DateTime.Now;
                   senddatatime2 = DateTime.Now;
                   this.Sendstate = 0;
                   this.pack.Sendflag = 0;
                   int buflen = 0;
                   this.Msgindex = 13;
                   this.changelistencity = 0;
                   changecitytime = DateTime.Now;
                   logininitime = DateTime.Now;
                   bInitConfig = true;
                   //Byte[] packbuf = pack.InitCRC(ref buflen);
                   Byte[] packbuf = pack.InitLoginPack(this.Loginusername, this.Loginpassword, this.Computerkey, ref buflen);
                   Byte[] sendbuf = new Byte[buflen];
                   Array.Copy(packbuf, 0, sendbuf, 0, buflen);
                   login.ClientSend(sendbuf);


                   AddDebugInfo("连接成功");

                   Recvdatalen = 0;
                   this.Logincount++;

               }
               else
               {
                   indexport++;
               }
           


           }
            

        }

        public void InitUIAction(IUIAction p)
        {
            donetdata.InitUIAction(p);
            this.SetUIAction(p);
        }
        public void INetError(Exception ex)
        {
            //AddDebugInfo("连接错误");
            this.Sendstate = 2;
            this.Reconnecttime = System.Environment.TickCount;
      

        }
        public void IDoPackData(Byte[] data, int len)
        {
            System.Console.WriteLine("IDoPackData");
            Recvdatalen += len;
            if (data[0] > 0)
            {
                try
                {
                    int dataoffset = 0;
                    while (dataoffset < len)
                    {
                        int datalen = Convert.ToInt32(data[dataoffset + 1] | (data[dataoffset + 2]) << 8);

                        int datacmd = Convert.ToInt32(data[dataoffset]);

                        if (datalen > 0 && datacmd > 0)
                        {
                            Byte[] copydata = new Byte[datalen];
                            Buffer.BlockCopy(data, dataoffset + 3, copydata, 0, datalen);

                            if (datacmd == 0x86 || datacmd == 0x76)
                            {

                                int readoffset = 0;
                                while (readoffset < datalen)
                                {


                                    Byte[] citydata = new Byte[0x8];
                                    Buffer.BlockCopy(copydata, readoffset + 0xA, citydata, 0, 0x8);


                                    int end = 0;
                                    int encodeend = 0;
                                    for (int i = readoffset + 0x12; i < datalen; i++)
                                    {
                                        if (copydata[i] == 0)
                                        {
                                            end = i;
                                            break;
                                        }
                                        if (encodeend == 0 && copydata[i] == 0x19)
                                        {
                                            encodeend = i;
                                        }
                                    }
                                    int encodedatalen = encodeend - readoffset - 0x12;
                                    Byte[] encodedata = new Byte[encodedatalen];
                                    Buffer.BlockCopy(copydata, readoffset + 0x12, encodedata, 0, encodedatalen);

                                    String call = pack.UncrypteData(encodedata);
                                    encodeend = encodeend + 1;

                                    int infodatalen = 0;
                                    if (datacmd == 0x76)
                                    {
                                        end = datalen;
                                        infodatalen = datalen - encodedatalen - 0x12 - 1;
                                    }
                                    else
                                        infodatalen = end - encodeend;

                                    Byte[] infodata = new Byte[infodatalen];
                                    Buffer.BlockCopy(copydata, encodeend, infodata, 0, infodatalen);

                                    readoffset = end + 1;

                                    Monitor.Enter(wuliuinfo);
                                    PeiHuoTemple p = new PeiHuoTemple();
                                    p.content = System.Text.Encoding.Default.GetString(infodata);
                                    p.innerphone = call;
                                    wuliuinfo.Add(p);
                                    Monitor.Exit(wuliuinfo);

                                    

                                    System.Console.WriteLine(p.content);
                                }

                                System.Diagnostics.Debug.WriteLine("收到0x86 or 0x76.");

                            }
                            else if (datacmd == 0x80)
                            {
                                Int32[] countdata = { 0, 0 };// 分别是当前地区的所有信息,全国总信息数量
                                Buffer.BlockCopy(copydata, 0xF0, countdata, 0, 8);
                                curcitycount = countdata[0];
                                allcount = countdata[1];
                                if (this.pack.Sendflag == 0)
                                    this.pack.Sendflag = copydata[0];

                                System.Console.Write("count:");
                                System.Console.Write(countdata[0]);
                                System.Console.Write("allcount:");
                                System.Console.Write(countdata[1]);
                                System.Console.WriteLine("收到0X80.");


                            }
                            else if (datacmd == 0x8B)
                            {
                                Int32[] tdata = { 0 };
                                Buffer.BlockCopy(copydata, 0, tdata, 0, 4);

                                curcitycount = tdata[0];
                                curcitycount = pack.getMsgCount(curcitycount);
                                System.Console.Write("curcitycount:");
                                System.Console.Write(curcitycount);

                                System.Diagnostics.Debug.WriteLine("收到0x8B.");

                            }
                            else
                            {
                                System.Console.WriteLine("other cmd");
                            }

                        }
                        dataoffset = dataoffset + datalen + 3;



                    }
                }
                catch (System.Exception ex)
                {
                    FileStream  f = File.Open("c:\\error.dat", FileMode.Create);
                    f.Write(data, 0, data.Length);
                    f.Close();

                    System.Console.WriteLine(ex.Message);
                    System.Console.WriteLine(ex.StackTrace);
                    System.Console.WriteLine("接收处理 Exception");

                    
                }
 
                if (this.Sendstate == 0)
                {
                    int buflen = 0;
                    //Byte[] packbuf = pack.InitloginCRC(ref buflen);
                    Byte[] packbuf = pack.InitLoginPack2(this.Loginusername, this.Loginpassword, this.Computerkey,ref buflen);

                    Byte[] sendbuf = new Byte[buflen];
                    Array.Copy(packbuf, 0, sendbuf, 0, buflen);

                    login.ClientSend(sendbuf);

                    this.sendstate = 1;

                    AddDebugInfo("成功登陆");



                }
                else if (this.Sendstate == 1)
                {

                }
            }

            
        }
        
    }

    /// <summary>
    /// 检测服务器是否可以连接.
    /// </summary>
    class CheckNet : IDoPack,IInitUIAction
    {
        private NetClient login1 = new NetClient();
        private NetClient login2 = new NetClient();
        private NetClient login3 = new NetClient();
        private PackManger pack = new PackManger();
        private DoNetData donetdata = new DoNetData();
      
        
        public CheckNet()
        {
            
        }
        public void Close()
        {
            login1.CloseClient();
            login2.CloseClient();
            login3.CloseClient();
        }
        public void InitUIAction(IUIAction p)
        {
            donetdata.InitUIAction(p);
        }
        public void IDoPackData(Byte[] data, int len)
        {
            donetdata.DoXmlData(data);
        }
        public void init()
        {
            
            System.Diagnostics.Debug.WriteLine("检测网络.");

            
            string result = pack.InitLogin("txtest", "北京");
            //////////////////////////////////////////////////////////////////////////
            int lendd = result.Length;


            login1.InitNet("123.130.126.79", 8098, NetClient.NetMode.UDP_CLIENT);
            login1.Idopack = this;
            login1.ClientSend(result);

            login2.InitNet("123.130.126.79", 80, NetClient.NetMode.UDP_CLIENT);
            login3.Idopack = this;
            login2.ClientSend(result);

            login3.InitNet("123.130.126.79", 997, NetClient.NetMode.UDP_CLIENT);
            login3.Idopack = this;
            login3.ClientSend(result);

        }

    }

    /// <summary>
    /// 处理返回检测连接的数据.
    /// </summary>
    class DoCanConnectXML : UIAction,IInitUIAction,IDoXML,IState
    {
        public void Run()
        {

        }
        public void InitUIAction(IUIAction p)
        {
            this.SetUIAction(p);
        }
        public Boolean DoXML(string xmldata)
        {
            System.Diagnostics.Debug.WriteLine("检测网络成功.");

            this.GetUIAction().DeleteDoXML(this);

            this.GetUIAction().LoginGetTicket();

            System.Diagnostics.Debug.WriteLine("开始登陆获取临时ID.");

            this.GetUIAction().SetState(StateManager.STATE_MODE.STATE_LOGIN_TICKET);
            
            return true;
        }
    }

 

    
}
